const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const morgan = require('morgan');
const path = require('path');

// 创建 Express 应用
const app = express();

// 基础中间件
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));

// 静态文件
// app.use(express.static(path.join(__dirname, '../public')));

//解决CSP + CORP 限制了跨域加载图片
app.use('/uploads', express.static('public/uploads', {
  setHeaders: (res) => {
    res.set('Access-Control-Allow-Origin', '*');
    res.set('Cross-Origin-Resource-Policy', 'cross-origin');
    res.removeHeader('Content-Security-Policy'); // 或者放宽 img-src
  }
}));
app.use('/images', express.static('public/images', {
  setHeaders: (res) => {
    res.set('Access-Control-Allow-Origin', '*');
    res.set('Cross-Origin-Resource-Policy', 'cross-origin');
    res.removeHeader('Content-Security-Policy'); // 或者放宽 img-src
  }
}));


app.use(express.static('public'));  //这样可以访问public/uploads的图片

// 路由
app.use(express.json()); 
const apiRouter = require('./routes/api');
app.use('/api', apiRouter);


const uploadRouter = require('./routes/upload');
app.use('/api', uploadRouter);

//测试路由
const dbTestRouter = require('./routes/dbTest');
app.use('/api', dbTestRouter);
// app.use('/public', express.static('public'));



module.exports = app;